require File.join(Rails.root, 'lib', 'authenticated_system.rb')

class ApplicationController < ActionController::Base
  protect_from_forgery 
  #TODO see http://stackoverflow.com/questions/6589522/rails-3-protect-from-forgery-not-doing-anything# See ActionController::RequestForgeryProtection for details
    
  
  helper :all # include all helpers, all the time

  rescue_from ActiveRecord::RecordNotFound, :with => :show_errors

  include AuthenticatedSystem

  before_filter :set_locale


  def show_errors
      render :partial => 'shared/record_not_found', :layout => 'application', :status => 404
  end

  def set_locale
    locale = params[:locale] || 'en'
    I18n.locale = locale
  end

  def get_browser_locale
    preferred_locale = nil
    if browser_locale = request.headers['HTTP_ACCEPT_LANGUAGE']
      preferred_locale = %w(en es fr de).
              select { |i| browser_locale.include?(i) }.
              collect { |i| [i, browser_locale.index(i)] }.
              sort { |a, b| a[1] <=> b[1] }.
              first
    end
    preferred_locale.try(:first) || 'en'
  end

  #returns a string
  def get_location_by_ip
    ip=request.remote_ip
    begin
      "#{request.location.city}, #{request.location.country}"
    rescue Exception => ex
         logger.error "Error when geocoding ip #{ip}. Details: #{ex.message}"
    end
  end


  def style_header(xml, ballon_text)
    colors_table=SoundLevel::COLORS_HTML #if COLORS_HTML is not CONSTANT BUT a FUnction
    SoundLevel.loudness_index_range{ |min, max, idx|
      color=colors_table[idx]
      color="ff"+color[5..6]+color[3..4]+color[1..2]
      #color="ff"+color[1..7]
      xml.Style(:id=>"db_index_#{idx}") {
        xml.IconStyle{
          xml.color(color)
          xml.scale("1")
          xml.Icon{
            xml.href("http://www.google.com/mapfiles/kml/shapes/dot.png")
          }
        }
        xml.BalloonStyle{
          xml.text { |x| x<<ballon_text}
        }
      }
    }
  end

  def get_icon_style(measure)
  end


  # ------------ user authentication functions ---------------
  def admin?
    if current_user && current_user.role == "admin"
      true
    else
      false
    end
  end
  def iscopeadmin?
    if current_user && (current_user.role == "admin" or current_user.role == "iscopeadmin")
      true
    else
      false
    end
  end

  def user_iscopeadmin?(user)
    if user && (user.role == "admin" or user.role == "iscopeadmin")
      true
    else
      false
    end
  end

  def owner?(id)
    if current_user.id == id
      true
    else
      false
    end
  end

  def admin_or_owner?(id)
    if admin? || owner?(id)
      true
    else
      false
    end
  end
  # ----------------- end user authentication functions -----------
end
